<?php
/**
 * Created by PhpStorm.
 * User: EDZ
 * Date: 2020/6/22
 * Time: 17:20
 */

namespace DesignPatterns\Behavioral\Observer;


class Subject
{
    /** @var array */
    private $observers;

    /** @var int */
    private $state;

    public function __construct()
    {
        $this->observers = array();
    }

    public function getState() {
        return $this->state;
    }

    public function setState($state) {
        $this->state = $state;
        $this->notifyAllObservers();
    }

    public function attach(Observer $observer) {
        array_push($this->observers, $observer);
    }

    public function detach(Observer $observer) {
        for ($i = 0, $n = count($this->observers); $i < $n; $i++) {
            $name1 = (new \ReflectionObject($this->observers[$i]))->getName();
            $name2 = (new \ReflectionObject($observer))->getName();
            if (strcmp($name1, $name2)==0) {
                unset($this->observers[$i]);
                break;
            }
        }
    }

    public function notifyAllObservers() {
        /** @var $ob Observer */
        foreach ($this->observers as $ob) {
            $ob->update();
        }
    }
}